﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using SqlSugar;
using System.Linq;
using VueAdminService.Attributes;
using VueAdminService.DTO;
using VueAdminService.Utils;
using VueAdminService.VO;

namespace VueAdminService.Controllers
{
	[ApiController]
	[Route("api/[controller]")]
	[TokenRequired]
	public class DictController : BaseController
	{
		public DictController(IServiceProvider serviceProvider) : base(serviceProvider) { }

		/// <summary>
		/// 获取字典树
		/// </summary>
		/// <param name="keyword">关键字</param>	
		/// <returns></returns>
		[HttpGet("tree")]
		public ResponseResult<List<DictDTO>> GetTree(string? keyword)
		{
			try
			{
				var list = _dbClient.Queryable<DictDTO>()
					.WhereIF(!string.IsNullOrWhiteSpace(keyword), d => d.Code.Contains(keyword) || d.Name.Contains(keyword))
					.ToTree(d => d.Children, d => d.ParentId, null);

				return SuccessResult(list);
			}
			catch (Exception ex)
			{
				LogError(ex, "获取字典树失败");
				return ErrorResult<List<DictDTO>>("获取字典树失败", null);
			}
		}
		/// <summary>
		/// 根据一级字典代码获取二级字典列表
		/// </summary>
		/// <param name="code">字典代码</param>
		/// <returns></returns>
		[HttpGet("getByCode")]
		public ResponseResult<List<DictDTO>> GetListByCode(string code)
		{
			try
			{
				var master = _dbClient.Queryable<DictDTO>().First(d => d.Code == code);
				if (master == null)
				{
					return FailedResult<List<DictDTO>>("未查询到数据", null);
				}
				var list = _dbClient.Queryable<DictDTO>()
					.Where(d => d.ParentId == master.DictId)
					.ToList();

				return SuccessResult(list);
			}
			catch (Exception ex)
			{
				LogError(ex, "获取数据字典失败");
				return ErrorResult<List<DictDTO>>("获取数据字典失败", null);
			}
		}
		/// <summary>
		/// 添加主字典
		/// </summary>
		/// <param name="vo"></param>
		/// <returns></returns>
		[HttpPost]
		public ResponseResult<bool> AddFirst([FromBody] RequestAddDictVO vo)
		{
			try
			{
				if (string.IsNullOrWhiteSpace(vo.Code) || string.IsNullOrWhiteSpace(vo.Name))
				{
					return FailedResult("字典代码或名称不能为空", false);
				}

				var dict = _dbClient.Queryable<DictDTO>().First(d => d.Code == vo.Code);
				if (dict != null)
				{
					return FailedResult("已存在相同代码的主字典", false);
				}

				_dbClient.Insertable<DictDTO>(new DictDTO()
				{
					DictId = SnowFlakeSingle.Instance.NextId().ToString(),
					Code = vo.Code,
					Name = vo.Name,
					Bak = vo.Bak,
				}).ExecuteCommand();

				return SuccessResult(true);
			}
			catch (Exception ex)
			{
				LogError(ex, "添加主字典失败");
				return ErrorResult("添加主字典失败", false);
			}
		}
		/// <summary>
		/// 添加字典明细
		/// </summary>
		/// <param name="vo"></param>
		/// <returns></returns>
		[HttpPost("child")]
		public ResponseResult<bool> AddChild([FromBody] RequestAddDictChildVO vo)
		{
			try
			{
				if (string.IsNullOrWhiteSpace(vo.Code) || string.IsNullOrWhiteSpace(vo.Name))
				{
					return FailedResult("字典代码或名称不能为空", false);
				}

				var dict = _dbClient.Queryable<DictDTO>().First(d => d.Code == vo.Code && d.ParentId == vo.ParentId);
				if (dict != null)
				{
					return FailedResult("已存在相同代码的字典明细", false);
				}
				_dbClient.Insertable<DictDTO>(new DictDTO()
				{
					DictId = SnowFlakeSingle.Instance.NextId().ToString(),//Guid.NewGuid().ToString("N"),
					Code = vo.Code,
					Name = vo.Name,
					Bak = vo.Bak,
					ParentId = vo.ParentId,
				}).ExecuteCommand();
				return SuccessResult(true);
			}
			catch (Exception ex)
			{
				LogError(ex, "添加字典明细失败");
				return ErrorResult("添加字典明细失败", false);
			}

		}
		/// <summary>
		/// 修改数据字典
		/// </summary>
		/// <param name="vo"></param>
		/// <returns></returns>
		[HttpPut]
		public ResponseResult<bool> UpdateDict([FromBody] RequestEditDictVO vo)
		{
			try
			{
				//if (string.IsNullOrWhiteSpace(vo.DictId))
				//{
				//	return FailedResult("字典Id不能为空", false);
				//}
				if (string.IsNullOrWhiteSpace(vo.Code) || string.IsNullOrWhiteSpace(vo.Name))
				{
					return FailedResult("字典代码或名称不能为空", false);
				}

				var dict = _dbClient.Queryable<DictDTO>().First(d => d.DictId == vo.DictId);
				if (dict == null)
				{
					return FailedResult("字典不存在", false);
				}
				_dbClient.Updateable<DictDTO>(new DictDTO()
				{
					DictId = dict.DictId,
					ParentId = dict.ParentId,
					Code = vo.Code,
					Name = vo.Name,
					Bak = vo.Bak,
				}).IgnoreColumns(d => new { d.ParentId })
				.ExecuteCommand();
				return SuccessResult(true);
			}
			catch (Exception ex)
			{
				LogError(ex, "修改字典失败");
				return ErrorResult("修改字典失败", false);
			}
		}
		/// <summary>
		/// 删除数据字典
		/// </summary>
		/// <param name="dictId">字典Id</param>
		/// <returns></returns>
		[HttpDelete("{dictId}")]
		public ResponseResult<bool> Delete(string dictId)
		{
			try
			{
				var dict = _dbClient.Queryable<DictDTO>().First();
				if (dict == null)
				{
					return FailedResult("数据字典不存在", false);
				}
				var list = _dbClient.Queryable<DictDTO>()
					.Where(d => d.DictId == dictId)
					.ToTree(d => d.Children, d => d.ParentId, null);
				if (list != null && list.Count > 0 && list[0].HasChildren)
				{
					return FailedResult("当前字典还有子字典，不能删除", false);
				}
				var result = _dbClient.Deleteable<DictDTO>(d => d.DictId == dictId).ExecuteCommand();
				return SuccessResult(true);

			}
			catch (Exception ex)
			{
				LogError(ex, "删除数据字典失败");
				return ErrorResult("删除数据字典失败", false);
			}
		}
	}
}
